/**
 * Created by MyPC on 2017/7/16.
 */
var express = require('express');
var router = express.Router();
let logger = require('log4js').getLogger('tagRoutes');
let Snowflake = require('node-snowflake').Snowflake;
let CategoryModel = require('../../schemas/category');
let response = require('../../common/responseJson');

router.get('/all', function (req, res, next) {
  let query = CategoryModel.find({

  }).exec(function (err, result) {
    if(err){
      logger.error('查询tag表报错:', err);
      response.error(res);
    }else{
      response.success(res, result);
    }
  });
});

router.post('/', function (req, res, next) {
  if(!req.body.alias){
    req.body.alias = Snowflake.nextId();
  }
  let img = req.body.img;
  if(img){
    req.body.img = img.replace(/\\/g, '/');
  }
  console.log(img);
  var category = new CategoryModel(req.body);
  let query = category.save(function (err, result) {
    if(err){
      logger.error('保存category表报错:', err);
      response.error(res);
    }else{
      response.success(res, result);
    }
  });
});

router.put('/:id', function (req, res, next) {
  let id = req.params.id;
  let name = req.body.name;
  let alias = req.body.alias;
  let link = req.body.link;
  let img = req.body.img;
  let isSecret = req.body.isSecret;
  isSecret = Boolean(isSecret);
  if(!id){
    returnJson(res, 'id不能为空');
    return;
  }
  if(!name){
    returnJson(res, '名称不能为空');
    return;
  }
  if(!alias){
    alias = Snowflake.nextId();
  }
  let updateParam = {
    'name': name,
    'alias': alias,
    'link': link,
    'img': img,
    'isSecret': isSecret
  };
  CategoryModel.update({_id: id}, updateParam);
  CategoryModel.then(function (result) {
    response.success(res, result);
  }).catch(function (err) {
    logger.error('修改主题报错,id:%s, body:%s , error:%s', id, JSON.stringify(updateParam), err);
    response.error(res);
  })
});


router.delete('/:id', function (req, res, next) {
  let id = req.params.id;
  let promise = CategoryModel.remove({_id: id});
  promise.then(function(result){
    response.success(res, result);
  }).catch(function (err) {
      logger.error('删除主题出错,id:%s, error:%s', id, err);
      response.error(res);
  });
});

module.exports = router;
